package com.xinshujia.config.adapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-26 17:07       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 时间戳适配器
 */
public class TimestampAdapter implements JsonDeserializer<LocalDateTime>, JsonSerializer<LocalDateTime> {
    private static final DateTimeFormatter formatPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));

    @Override
    public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        if (jsonElement.isJsonPrimitive() && jsonElement.getAsJsonPrimitive().isNumber()) {
            long timestamp = jsonElement.getAsLong();
            return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.of("Asia/Shanghai"));
        }else if(jsonElement.isJsonPrimitive() && jsonElement.getAsJsonPrimitive().isString()){
            return LocalDateTime.parse(jsonElement.getAsString(), formatPattern);
        }
        // 这里可以添加对字符串格式日期时间的处理
        throw new JsonParseException("Expected a number representing a UNIX timestamp");

    }

    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
     return new JsonPrimitive(formatPattern.format(localDateTime));
    }
}

